package cn.domypay.mail.thread;

import java.util.Properties;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;

import cn.domypay.back.log.DoMyPayLogger;
import cn.domypay.mail.base.SmtpBiz;
import cn.domypay.mail.base.SwanetAuthenticate;
import cn.domypay.mail.bean.Mailbox;
import cn.domypay.mail.conf.DomypayMail;

public class SmtpThread extends Thread{
	
	private static DoMyPayLogger logger = DoMyPayLogger.getLogger(SmtpThread.class);
	
	private Mailbox mailbox;
	
	private Properties mailProps;
	
	private Session session;
	
	public SmtpThread(Mailbox mailbox) {
		// TODO �Զ���ɹ��캯����
		this.mailbox = mailbox;
	}
	
	public void run()
	{
		try {
			check();
		} catch (MessagingException e) {
			// TODO �Զ���� catch ��
			logger.logInfo(e);
		}
	}
	public void check() throws MessagingException
	{
		SwanetAuthenticate pAuth = new SwanetAuthenticate(mailbox
				.getUsername(), mailbox.getPassword());
		
		SmtpBiz smtpBiz = new SmtpBiz();
		
		mailProps = new Properties();
		
		if(DomypayMail.NEED_SSL.equals(mailbox.getSmtpSsl()))
		{
			/**
			 * 如果需要进行ssl连接方式，获取ssl连接方式的smtp协议设置
			 */
			mailProps = smtpBiz.getSmtp_SslProp(mailbox);
			
		}else{
			/**
			 * 如果不需要进行ssl连接方式，获取普通smtp协议设置
			 */
			mailProps=smtpBiz.getSmtpProp(mailbox);
			
		}		
		session = Session.getInstance(mailProps, pAuth);
		/**
		 * 尝试发smtp验证是否成功
		 * 如果不成功返回结果
		 * 如果成功返回null
		 */
		smtpBiz.checkSmtp(session, mailbox);
		
	}
	public void smtpStop() throws NoSuchProviderException, MessagingException{
		
		session.getTransport("smtp").close();
		this.interrupt();
		
	}
}
